// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: Apache-2.0

package resource_dao

import (
	"context"
	"regexp"

	"gitcode.com/lvupclub/lvup-api/dao/common"
	"gitcode.com/lvupclub/proto-gen-go.git/src/resource_card_api"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

type BasicCardInfoDbItem struct {
	Title   string `bson:"title"`
	Content string `bson:"content"`
}

type CardInfoDbItem struct {
	CardId     string              `bson:"_id"`
	ResourceId string              `bson:"resourceId"`
	BasicInfo  BasicCardInfoDbItem `bson:"basicInfo"`
	CreateTime int64               `bson:"createTime"`
	UpdateTime int64               `bson:"updateTime"`
}

func (item *CardInfoDbItem) ToCardInfo(withContent bool) *resource_card_api.CardInfo {
	basicInfo := &resource_card_api.BasicCardInfo{
		Title: item.BasicInfo.Title,
	}
	if withContent {
		basicInfo.Content = item.BasicInfo.Content
	}
	return &resource_card_api.CardInfo{
		CardId:     item.CardId,
		BasicInfo:  basicInfo,
		LinkList:   []*resource_card_api.ReleateCardLink{},
		CreateTime: item.CreateTime,
		UpdateTime: item.UpdateTime,
	}
}

type _CardInfoDao struct {
	mc *mongo.Collection
}

func newCardInfoDao(db *mongo.Database) (*_CardInfoDao, error) {
	mc := db.Collection(common.DB_NS_RESOURCE + "card_info")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"resourceId", 1}, {"createTime", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_CardInfoDao{mc: mc}, nil
}

func (db *_CardInfoDao) Insert(ctx context.Context, dbItem *CardInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_CardInfoDao) Exist(ctx context.Context, resourceId, cardId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"resourceId": resourceId, "_id": cardId})
	return count > 0, err
}

func (db *_CardInfoDao) Get(ctx context.Context, resourceId, cardId string) (*CardInfoDbItem, error) {
	retItem := &CardInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"resourceId": resourceId, "_id": cardId}).Decode(retItem)
	return retItem, err
}

func (db *_CardInfoDao) Remove(ctx context.Context, resourceId, cardId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"resourceId": resourceId, "_id": cardId})
	return err
}

func (db *_CardInfoDao) RemoveByResource(ctx context.Context, resourceId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"resourceId": resourceId})
	return err
}

func (db *_CardInfoDao) Count(ctx context.Context, resourceId string, filterByKeyword bool, keyword string, fiterByCardIdList bool, cardIdList []string) (uint32, error) {
	if fiterByCardIdList && len(cardIdList) == 0 {
		return 0, nil
	}
	query := bson.M{"resourceId": resourceId}
	if fiterByCardIdList {
		query["_id"] = bson.M{"$in": cardIdList}
	}
	if filterByKeyword {
		query["basicInfo.title"] = bson.Regex{
			Pattern: regexp.QuoteMeta(keyword),
			Options: "i",
		}
	}
	count, err := db.mc.CountDocuments(ctx, query)
	return uint32(count), err
}

func (db *_CardInfoDao) List(ctx context.Context, resourceId string, filterByKeyword bool, keyword string, fiterByCardIdList bool, cardIdList []string, offset, limit int64) ([]*CardInfoDbItem, error) {
	if fiterByCardIdList && len(cardIdList) == 0 {
		return []*CardInfoDbItem{}, nil
	}
	query := bson.M{"resourceId": resourceId}
	if fiterByCardIdList {
		query["_id"] = bson.M{"$in": cardIdList}
	}
	if filterByKeyword {
		query["basicInfo.title"] = bson.Regex{
			Pattern: regexp.QuoteMeta(keyword),
			Options: "i",
		}
	}
	cursor, err := db.mc.Find(ctx, query, options.Find().SetSkip(offset).SetLimit(limit).SetSort(bson.M{"createTime": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*CardInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_CardInfoDao) UpdateBasic(ctx context.Context, resourceId, cardId string, basicItem *BasicCardInfoDbItem, updateTime int64) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"resourceId": resourceId, "_id": cardId}, bson.M{
		"$set": bson.M{
			"basicInfo":  basicItem,
			"updateTime": updateTime,
		},
	})
	return err
}
